/**
 * Created with JetBrains WebStorm.
 * User: Eric
 * Date: 02/02/13
 * Time: 17:17
 * To change this template use File | Settings | File Templates.
 */

/*
 * This file is a test of un Dao implementation
 * We need the mysql module
 */


// We create a connection
var connector = require('./connector');
var connection = connector.connection();
// We need our model
var Game = require("./Game");


var findDefaultMoney = function(callback){
    var game = new Game(); // Our model that we can instanciate
    connection.query('SELECT * from game', function(err, rows) { // we do the query
        if (err) throw err; // if there is an error we throw it
        if (rows.length === 1){ // there is one result
            game.init(rows[0]); // we init the model with the row
        }else{
            game = null; // We didin't find the user
        }
        callback(game); // Callback basicaly it's the end of the controleur
    });
}



var persistGameSettings = function(game, callback){

    var post  = {money: game.money};

 connection.query('SELECT * from game', function(err, rows) {

    if ( rows.length != 1){
        connection.query('INSERT INTO game SET ?', post, function(err, rows, fields){

            if (err) throw err; // if there is an error we throw it
            callback(game); // Callback basicaly it's the end of the controleur
        });
    }else{

        connection.query('update game SET ?',[post,game.money], function(err, rows, fields){

            if (err) throw err; // if there is an error we throw it
            callback(game); // Callback basicaly it's the end of the controleur
        });
    }

});
};

exports.persistGameSettings = persistGameSettings;
exports.findDefaultMoney = findDefaultMoney;

